<template>
  <div class="register-container">
    <div class="register-box">
      <h2>注册账号</h2>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :prefix-icon="User" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" :prefix-icon="Message" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="验证码" prop="verifyCode">
          <div class="verify-code-container">
            <el-input v-model="form.verifyCode" placeholder="请输入验证码" :prefix-icon="Key" />
            <el-button type="primary" :disabled="countdown > 0 || loading" @click="sendVerifyCode">
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" class="submit-btn" @click="handleRegister">
            注册
          </el-button>
        </el-form-item>

        <div class="login-link">
          已有账号？
          <el-button link type="primary" @click="goToLogin">立即登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Message, Lock, Key } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/modules/auth'
import userService from '@/services/userService'

const router = useRouter()
const authStore = useAuthStore()
const emit = defineEmits(['custom-event'])
const isRegister = ref(true)
const loading = ref(false)
const countdown = ref(0)
const formRef = ref(null)

const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  verifyCode: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '请输入正确的验证码', trigger: 'blur' }
  ]
}

// 发送验证码
const sendVerifyCode = async () => {
  try {
    if (!form.email) {
      ElMessage.warning('请先输入邮箱地址')
      return
    }
    loading.value = true

    const response = await userService.sendVerifyCode(form.email)

    if (response.success) {
      ElMessage.success('验证码已发送，请查收邮件')
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  } finally {
    loading.value = false
  }
}

// 注册
const handleRegister = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true

    const response = await userService.register({
      username: form.username,
      email: form.email,
      password: form.password,
      verifyCode: form.verifyCode
    })

    if (response.success) {
      ElMessage.success('注册成功，请登录')
      // 触发自定义事件，将 isRegister 设为 true 以显示登录页
      emit('custom-event', true)
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  } finally {
    loading.value = false
  }
}

// 返回登录
const goToLogin = () => {
  emit('custom-event', true)
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: var(--el-bg-color);
}

.register-box {
  width: 400px;
  padding: 40px;
  border-radius: 8px;
  background-color: var(--el-bg-color-overlay);
  box-shadow: var(--el-box-shadow-light);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: var(--el-text-color-primary);
}

.verify-code-container {
  display: flex;
  gap: 10px;
}

.verify-code-container .el-input {
  flex: 1;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: var(--el-text-color-regular);
}

:deep(.el-input__wrapper) {
  background-color: var(--el-fill-color-blank);
}

:deep(.el-form-item__label) {
  color: var(--el-text-color-regular);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-input__inner) {
  height: 40px;
  color: var(--el-text-color-primary);
}
:deep(.el-input__wrapper) {
  background: var(--el-fill-color-light);
  color: var(--el-text-color-primary);
  outline: none;
}
</style>
